package com.fist.eth.flutter_plugin_eth_wallet.utils

import android.util.Log
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import org.web3j.crypto.Credentials
import org.web3j.crypto.Keys
import java.math.BigInteger
import java.util.concurrent.Future

object TokenContractUtils {
    private val TAG: String = this.javaClass.simpleName

    var mUrl: String = ""
    var mAddress: String = ""
    var mTokenName: String = ""

    fun config(url: String, address: String, tokenName: String) {
        mUrl = url
        mAddress = address
        mTokenName = tokenName
    }

    fun loadContract(wallet: TokenWallet, gasPrice: BigInteger, gasLimit: BigInteger): TokenContract {
        val credentials = Credentials.create(wallet.keyPair)
        Log.i(TAG, "onClickDeploy: gasPrice = $gasPrice")
        Log.i(TAG, "onClickDeploy: GAS_LIMIT = $gasLimit")
        val web3j = Web3jUtils.getWeb3j(mUrl)
        return TokenContract.load(mAddress, web3j, credentials, gasPrice, gasLimit)
    }

//    fun loadContract(wallet: TokenWallet, gasPrice: BigInteger, gasLimit: BigInteger): Single<TokenContract> {
//        val credentials = Credentials.create(wallet.keyPair)
//        Log.i(TAG, "onClickDeploy: gasPrice = $gasPrice")
//        Log.i(TAG, "onClickDeploy: GAS_LIMIT = $gasLimit")
//        val web3j = Web3jUtils.getWeb3j(mUrl)
//        return Single.fromCallable { TokenContract.load(mAddress, web3j, credentials, gasPrice, gasLimit) }
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//    }

    fun balanceOf(contract: TokenContract, address: String): Single<BigInteger> {
        return Single.fromCallable { contract.balanceOf(Keys.toChecksumAddress(address)).send() }
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
    }
}
